package org.bite.book_controller.controller;


import lombok.extern.slf4j.Slf4j;
import org.bite.book_controller.model.BookInfo;
import org.bite.book_controller.model.PageResult;
import org.bite.book_controller.model.RequestPage;
import org.bite.book_controller.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@Slf4j
@RequestMapping("/book")
@RestController
public class BookController {
    @Autowired
    private BookService bookService;

    @RequestMapping("/getList")
    public List<BookInfo> getList(){

//        BookService bookService = new BookService();
        List<BookInfo> list = bookService.getList();
        return list;
    }
    @RequestMapping("/getListByPage")
    public PageResult<BookInfo> getListBuPage(RequestPage requestPage){
        log.info("getListBuPage 接受参数：{}",requestPage);
        return bookService.getListPage(requestPage);
    }

    @RequestMapping("addBook")
    public boolean addBook(BookInfo bookInfo){
        log.info("添加图书 接收参数：{}",bookInfo);
        if(!StringUtils.hasLength(bookInfo.getBookName()) || !StringUtils.hasLength(bookInfo.getAuthor()) ||
                bookInfo.getCount() == null || bookInfo.getPrice() == null ||
                !StringUtils.hasLength(bookInfo.getPublish())){
            return false;
        }
        Integer result = bookService.addBook(bookInfo);
        if(result > 0){
            return true;
        }else{
            log.error("添加图书失败");
            return false;
        }
    }
    @RequestMapping("/getBookInfo")
    public BookInfo getBookInfo(Integer bookId){
        log.info("getBookInfo,bookId:{}",bookId);
        BookInfo bookInfo = bookService.getBookInfo(bookId);
        if (bookInfo == null){
            log.info("图书信息为空");
            return new BookInfo();
        }
        return bookInfo;
    }
    @RequestMapping("/updateBook")
    public Boolean updateBook(BookInfo bookInfo){
        log.info("updateBook,bookInfo:{}",bookInfo);
//        if(bookInfo.getId() == null
//                || !StringUtils.hasLength(bookInfo.getBookName())
//                || !StringUtils.hasLength(bookInfo.getAuthor())
//                || !StringUtils.hasLength(bookInfo.getPublish())
//                || bookInfo.getCount()<0
//                || bookInfo.getPrice()==null
//        ){
//            return false;
//        }
        if(bookInfo.getId() == null){
            log.warn("id不能为空");
            return false;
        }
        try{
            Integer result = bookService.updateBook(bookInfo);
            if(result > 0){
                return true;
            }
            return false;
        }catch (Exception e){
            log.error("updateBook error", e);
            return false;
        }
    }
}
